package com.example.mychat.component;

import org.springframework.stereotype.Component;
import org.springframework.web.socket.WebSocketSession;

import java.net.http.WebSocket;
import java.util.concurrent.ConcurrentHashMap;

@Component
public class OnLineUserMapper {

    //创建hashMap
    private ConcurrentHashMap<Integer, WebSocketSession> sessions = new ConcurrentHashMap<>();

    //用户上线，给这个哈希表插入键值对
    public void online(int userId, WebSocketSession webSocket){
        if(sessions.get(userId)!=null){
            //此时说明用户已经登录了，不记录这个映射关系后续就收不到任何消息
            System.out.println("用户 " + userId + "已经登录，登录失败");
            return;
        }
        sessions.put(userId,webSocket);
        System.out.println("登录的用户为: "+ userId);

    }


    //用户下线,移除哈希表中的键值对
    public void offline(int userId,WebSocketSession webSocket){
        WebSocketSession webSocket1 = sessions.get(userId);
        if(webSocket1==webSocket){
            sessions.remove(userId);
            System.out.println("确定是本人登录，来移除哈希表中的键值对" + userId + "下线");
        }
    }

    //根据userid获取到webSocketSession
    public WebSocketSession getSession(int userId){
        System.out.println("为获得WebSocketSession中的session传入的userId : " + userId);

        return sessions.get(userId);

    }

}
